package com.allianz.webapps.controllers;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import sun.misc.BASE64Decoder;
import cn.org.bjca.anysign.client.net.utils.FileUtil;
import cn.org.bjca.anysign.client.security.SecurityEngineDeal;
import cn.org.bjca.anysign.model.AnywriteSignInfo;
import cn.org.bjca.pdf.model.DocumentType;

import com.allianz.frame.utils.ApplicationContextUtil;
import com.allianz.frame.utils.ImageUploadUtil;
import com.allianz.frame.utils.PropertiesUtil;
import com.allianz.frame.utils.StringUtil;
import com.allianz.webapps.https.interfaces.bjca.BJCApojo;
import com.allianz.webapps.https.interfaces.bjca.PdfMessage;
import com.allianz.webapps.https.interfaces.type001.pojo.User;
import com.allianz.webapps.https.interfaces.util.ObjectUtil;
import com.allianz.webapps.https.interfaces.util.SftpUtil;
import com.allianz.webapps.orderspojo.AppBase;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping(value = "main")
public class ShadowUploadController {
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private ObjectUtil objectUtil;

	protected final Logger log = LoggerFactory.getLogger(getClass());
	//http://localhost:8080/pad_marketing/main/upload_one.action
	@RequestMapping("/upload_one")
	@ResponseBody
	public String upload_one(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//获取保单号
		String policyRef = request.getParameter("policyRef");
		Assert.notNull(policyRef, "保单号未传入");
			log("policyRef保单号:"+policyRef);
		//获取投保单号
		String insured = request.getParameter("insured");
				log("insured投保单号:"+insured);
		File f = new File(PropertiesUtil.getResourcePath()+"private/photo_temp/"+policyRef+"/");
		if(f.exists()){
			if(f.isFile()){
				f.delete();
			}
		}else{
			f.mkdirs();
		}
		String image = request.getParameter("image");//这个就是前端传来的base64图片数据
		image = image.replaceAll("data:image/png;base64,","");
		String idtype = request.getParameter("idtype");

		if("11".equals(idtype)){//"投保人身份证正面"
			idtype = "tbNationalIDfront";
		}else if("12".equals(idtype)){//投保人身份证反面
			idtype = "tbNationalIDback";
		}else if("13".equals(idtype)){//投保人护照正面
			idtype = "tbPassportfront";
		}else if("14".equals(idtype)){//投保人护照反面
			idtype = "tbPassportback";
		}else if("15".equals(idtype)){//投保人军官证正面
			idtype = "tbMilitaryIDfront";
		}else if("16".equals(idtype)){//投保人军官证反面
			idtype = "tbMilitaryIDback";
		}else if("17".equals(idtype)){//投保人户口本首面
			idtype = "tbResidenceFirst";
		}else if("18".equals(idtype)){//投保人户口本本人页
			idtype = "tbResidenceMine";
		}else if("19".equals(idtype)){//投保人出生证正面
			idtype = "tbBirthCardFront";
		}else if("10".equals(idtype)){//投保人银行卡正面
			idtype = "tbCreditcardFront";
		}else if("32".equals(idtype)){//投保人港澳通行证正面
			idtype = "tbHongKongMacauLaissezPasserFront";
		}else if("33".equals(idtype)){//投保人港澳通行证反面
			idtype = "tbHongKongMacauLaissezPasserBack";
		}else if("31".equals(idtype)){//投保人台胞证
			idtype = "tbMTP";
		}else if("21".equals(idtype)){//被保人身份证正面
			idtype = "bbNationalIDfront";
		}else if("22".equals(idtype)){//被保人身份证反面
			idtype = "bbNationalIDback";
		}else if("23".equals(idtype)){//被保人护照正面
			idtype = "bbPassportfront";
		}else if("24".equals(idtype)){//被保人护照反面
			idtype = "bbPassportback";
		}else if("25".equals(idtype)){//被保人军官证正面
			idtype = "bbMilitaryIDfront";
		}else if("26".equals(idtype)){//被保人军官证反面
			idtype = "bbMilitaryIDback";
		}else if("27".equals(idtype)){//被保人户口本首面
			idtype = "bbResidenceFirst";
		}else if("28".equals(idtype)){//被保人户口本本人页
			idtype = "bbResidenceMine";
		}else if("29".equals(idtype)){//被保人出生证正面
			idtype = "bbBirthCardFront";
		}else if("35".equals(idtype)){//被保人港澳通行证正面
			idtype = "bbHongKongMacauLaissezPasserFront";
		}else if("36".equals(idtype)){//被保人港澳通行证反面
			idtype = "bbHongKongMacauLaissezPasserBack";
		}else if("34".equals(idtype)){//投保人台胞证
			idtype = "bbMTP";
		}else if("50".equals(idtype)){//被保人银行卡正面
			idtype = "bbCreditcardFront";
		}

		/*FileWriter fw = new FileWriter(PropertiesUtil.getResourcePath()+idtype+".txt");
		fw.write(image);
		fw.flush();
		fw.close();*/
		
		//  覆盖之前以拍过的照片		如果照片存在则删除原来的照片
		File file=new File(PropertiesUtil.getResourcePath()+"private/photo_temp/"+policyRef+"/");
		if(file.exists()){
			for (File fi : file.listFiles()) {
				if(fi.getName().contains(idtype)){
					fi.delete();
				}
			}
		}

		//data:image/png;base64
		String innerPath = idtype+"_"+new Date().getTime()+".jpg";
		String realPath = PropertiesUtil.getResourcePath()+"private/photo_temp/"+policyRef+"/"+innerPath;
		boolean upload_state = false;
		BASE64Decoder decoder = new BASE64Decoder();
		try{
			byte[] decodedBytes = decoder.decodeBuffer(image);
			for(int i=0;i<decodedBytes.length;++i){
				if(decodedBytes[i]<0){//调整异常数据  
                	decodedBytes[i]+=256;  
                }
			}
			FileOutputStream out = new FileOutputStream(realPath);
			out.write(decodedBytes);
			out.close();
			log.info("photo upload success.");
		}catch(Exception e){
			ServletOutputStream outputStream = response.getOutputStream();
			log.info("photo upload faild.");
			outputStream.close();
			innerPath = "";
			throw new Exception("图片上传失败");
		}finally{
			//ftpService.logout();
		}
		return innerPath;
	}

	//http://localhost:9000/pad_marketing/main/all_submit.action
	@RequestMapping("/all_submit")
	@ResponseBody
	public String all_submit(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request,HttpServletResponse response) throws Exception {
		String stutas = request.getParameter("stutas");
		String filePaths = request.getParameter("filePaths");
		//key为img4的是银行卡，为1160，其他为1163
		@SuppressWarnings("unchecked")
		Map<String,String> files = objectMapper.readValue(filePaths, Map.class);
		log("stutas:"+stutas);
		//更新状态
		if("N".equals(stutas)){
			AppBase appBase=objectMapper.readValue(jsonParam, AppBase.class);
			appBase.setUser((User)request.getSession().getAttribute("username"));
			log("AppId:"+appBase.getAppId());
			log("OrderId:"+appBase.getOrderId());
			log("Sign:"+appBase.getSign());
			
			
//------------------------第二次影像上传
			String policyRef=appBase.getPolicyRef();
			String preprintedNo=appBase.getPreprintedNo();
			String ip=ImageUploadUtil.getIP(request);
			log("policyRef:"+policyRef);
			log("preprintedNo:"+preprintedNo);
			log("ip:"+ip);
			
			ImageUploadUtil.imageUploadMethod(policyRef, preprintedNo, "U", ip,files);
			
			appBase.setStatus("P");
			String body=null;
			try{
				//body = objectUtil.requestParam(appBase, "app.updateStatus");
				//转线下流程要求走app.afterUploadDocs，以前的app.updateStatus废弃，新增返回appBase，查询返回的状态
				body = objectUtil.requestParam(appBase, "app.afterUploadDocs");
			}catch(Exception e){
				e.printStackTrace();
				throw new Exception("修改核心状态异常！");
			}
			return body;
		}
		return null;
	}

	//http://localhost:9000/pad_marketing/main/show_jpg.action?jpg_name=bbCreditcardFront_147744914233.jpg
	@RequestMapping("/show_jpg")
	public void show_jpg(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException,IOException {
		String jpg_name = request.getParameter("jpg_name");
		//展示jpg文件
		HttpSession hs = request.getSession();
		User u = (User)hs.getAttribute("username");
		if(u==null || StringUtil.isNull(u.getUserId())){
			return;
		}
		String userId = u.getUserId();
		File f = new File(PropertiesUtil.getResourcePath()+"private/photo_temp/"+userId+"/"+jpg_name);
		String filename = f.getName();
		log.info(filename);
		int length = 0;
		ServletOutputStream op = response.getOutputStream();
		response.setContentLength((int) f.length());
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "inline; filename="+jpg_name);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);

		byte[] bytes = new byte[1024];
		DataInputStream in = new DataInputStream(new FileInputStream(f));
		while ((in != null) && ((length = in.read(bytes)) != -1)) {
			op.write(bytes, 0, length);
		}
		op.close();
		in.close();
		response.flushBuffer();
	}

	//http://localhost:9000/pad_marketing/main/bjcapdf.action
	@RequestMapping("/bjcapdf")
	@ResponseBody
	public Map<String,String> bjcapdf(HttpServletRequest request,HttpServletResponse response) throws Exception{
		log.info("=======签字页面影像处理开始……");
		List<File> sftp_puload_pdf_list = new ArrayList<File>();
		log.debug("bjcapdf");
		String resourcePath = PropertiesUtil.getResourcePath();//app/azclportal_resource/resources/temp/
		String signedPDFpath = null;
		log(resourcePath);
		log.debug(resourcePath);

		ObjectMapper mapper = (ObjectMapper)ApplicationContextUtil.getBean("objectMapper");
		String json = request.getParameter("jsonParam");
		//log(bw,json);
		//log.debug(json);
		BJCApojo bjca = null;
		try{
			bjca = mapper.readValue(json,BJCApojo.class);
			String policyRef = bjca.getPolicyRef();
			//log(bw,bjca.toString());
			//log.debug(bjca.toString());
			//定位pdf：
			List<PdfMessage> pdfList = bjca.getPdfMessageList();
			for(PdfMessage p : pdfList){
				String encode = p.getEncode();//加密包
				String pdfURL = PropertiesUtil.getProperty("interfaceIP")+p.getPdfURL();//pdf链接，应该是内网
				log("pdfURL:==================="+pdfURL);
				String pdfType = p.getPdfType();//获取pdf类型
				
				
//--------------------------------------------------------------------------------------		
				
//				//未签名的pdf目录路径：
//				String unsignPdfDirectoryPath = resourcePath+"private/pdf/"+bjca.getInsured()+"/"+"unsign/";
//				//签名后的pdf目录路径：
//				String signedPdfDirectoryPath = resourcePath+"private/pdf/"+bjca.getInsured()+"/"+"signed/";
				
//-------------------------------------------------------------------------
				//未签名的pdf目录路径：
				String unsignPdfDirectoryPath = resourcePath+"private/pdf/"+policyRef+"_"+bjca.getInsured()+"/"+"unsign/";
				//签名后的pdf目录路径：
				String signedPdfDirectoryPath = resourcePath+"private/pdf/"+policyRef+"_"+bjca.getInsured()+"/"+"signed/";
				
				if(StringUtil.isNull(signedPDFpath)){
					signedPDFpath = signedPdfDirectoryPath;
				}
				log(unsignPdfDirectoryPath);
				log(signedPdfDirectoryPath);
				log.debug(signedPdfDirectoryPath);
				log.debug(unsignPdfDirectoryPath);
				
				File file1 = new File(unsignPdfDirectoryPath);
				File file2 = new File(signedPdfDirectoryPath);
				if(file1.exists()){
					if(file1.isFile()){
						file1.delete();
					}
				}else{
					file1.mkdirs();
				}

				if(file2.exists()){
					if(file2.isFile()){
						file2.delete();
					}
				}else{
					file2.mkdirs();
				}

				String unsignPdfPath = unsignPdfDirectoryPath + pdfType+".pdf";
				log.info("=======下载原始pdf，从"+pdfURL+"……");
				boolean b = saveUnsignPdf(pdfURL,unsignPdfPath);
				log.info("=======原始pdf下载完成……");	

				//生成加密后的pdf：
				String signedPdfPath = signedPdfDirectoryPath+pdfType+".pdf";
				sftp_puload_pdf_list.add(new File(signedPdfPath));

				log(unsignPdfPath);
				log(signedPdfPath);
				log.debug(unsignPdfPath);
				log.debug(signedPdfPath);

				//调用ca接口
				FileWriter fw = null;
				if(StringUtil.isNull(encode)){
					Map<String,String> map = new HashMap<String,String>();
					map.put("flag", "N");
					return map;
				}else{
					fw = new FileWriter(unsignPdfDirectoryPath + pdfType+".txt");
					fw.write(encode);
					fw.flush();
					fw.close();
				}
				log.info("=======调用CA接口开始……");	
				int repeat = 5;
				while(repeat>0){
					boolean result = bjcaInterface(unsignPdfDirectoryPath + pdfType+".txt",unsignPdfPath,signedPdfPath,bjca.getPolicyRef());
					if(result)
						break;
					repeat--;
					Thread.sleep(2000);
				}
				File signedPDF = new File(signedPdfPath);
				if(!(signedPDF.exists()&&signedPDF.length()>0))
					throw new Exception("签字异常！请稍后重试！");
				log.info("=======调用CA接口成功……");	
						
//				if(!b){
//					return "N";
//				} 
				//String imagePath = pdfDirectoryPath +"signed/"
				log.info("=======向signed目录存放图片开始……");
				List<String> photoList = p.getPhotoList();
				for(int i=0;i<photoList.size();i++){
					String photoPath = signedPdfDirectoryPath+i+pdfType+".jpg";
					log(photoPath);
					log.debug(photoPath);
					String jpg_base64 = photoList.get(i);
					if(StringUtil.notNull(jpg_base64)){
						saveImage(photoList.get(i),photoPath);	
					}
				}
				log.info("=======向signed目录存放图片结束……");
			}

			if(!"1164".equals(pdfList.get(0).getPdfType())){
				//修改订单状态
				AppBase appBase = new AppBase();
				appBase.setAppId(bjca.getAppId());
				appBase.setOrderId(bjca.getOrderId());
				appBase.setSign(bjca.getSign());

				log.info("=======上传sftp开始……");
				//signedPdfDirectoryPath
				String path=resourcePath+"private/pdf/"+policyRef+"_"+bjca.getInsured()+"/"+"signed/";
				SftpUtil.sftpUploadPdf(policyRef,path,1);
				log.info("=======上传sftp结束……");

//-------------------				 第一次影像上传                      -----------------------
				String ip = ImageUploadUtil.getIP(request);
				ImageUploadUtil.imageUploadMethod(policyRef, bjca.getInsured(), "S", ip,null);
				log.info("=======上传影像系统结束……");
				
				appBase.setStatus("U");
				String body=null;
				try {
					log.info("=======核心app.updateStatus接口调用开始……");
					body=objectUtil.requestParam(appBase, "app.updateStatus");
				} catch (Exception e) {
					e.printStackTrace();
					throw new Exception("保单状态更新失败！请重试!");
				}
				log.info("=======核心app.updateStatus接口调用结束……");
				JSONObject jsonobject = new JSONObject(body);
				//状态的判断有问题
				if(!("S").equals(jsonobject.getString("Status"))){
					throw new Exception(jsonobject.getString("ErrMsg"));
				}else {
					Map<String,String> map = new HashMap<String,String>();
					map.put("flag", "Y");
					return map;
				}
			}else{
				Map<String,String> map = new HashMap<String,String>();
				map.put("flag", "Y");
				return map;
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
	}

	/*@RequestMapping("xmlw")
	public void xmlw(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String ip = ImageUploadUtil.getIP(request);
		ImageUploadUtil.imageUploadMethod("000002881277", "BR0000102707", "U", ip);
	}*/
	
	@RequestMapping("/toUpload")
	public String toUpload() {
		return "/upload";
	}
	
	public static void main(String[] args) {
	}
	
	/**
	 * 图片上传测试
	 * @throws IOException 
	 */
	@RequestMapping(value = "uploadFileImg", method = RequestMethod.POST)
	@ResponseBody
	public void upload(MultipartHttpServletRequest multipartRequest, HttpServletResponse response,HttpServletRequest request) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		response.reset();
		String realPath = PropertiesUtil.getResourcePath()+"private/shadow_upload/";
		for(Iterator iterator = multipartRequest.getFileNames(); iterator.hasNext();) {
			String key = (String) iterator.next();
			MultipartFile multipartFile = multipartRequest.getFile(key);
			if(!multipartFile.isEmpty()) {
				saveFile(realPath, multipartFile);
			}
		}
		out.print("OK");
		out.flush();
		out.close();
	}
	
	public Boolean saveFile(String realPath, MultipartFile multipartFile) {
		String fileName = multipartFile.getOriginalFilename();
		fileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf('.'), fileName.length());
		try {
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(realPath, fileName));
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	//保存base64图片
	private boolean saveImage(String base64,String imagePath) throws Exception{
		//String image = request.getParameter("image");//这个就是前端传来的base64图片数据
		//image = image.replaceAll("data:image/png;base64,","");
		BASE64Decoder decoder = new BASE64Decoder();
		try{
			byte[] decodedBytes = decoder.decodeBuffer(base64);
			for(int i=0;i<decodedBytes.length;++i){  
				if(decodedBytes[i]<0){//调整异常数据  
                	decodedBytes[i]+=256;  
                }
			}
			FileOutputStream out = new FileOutputStream(imagePath);
			out.write(decodedBytes);
			out.close();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
	}

	//下载pdf链接
	private boolean saveUnsignPdf(String pdfURL,String pdfPath){
		try{
			URL tirc = new URL(pdfURL);
			InputStream is = tirc.openStream();
			FileOutputStream fos = new FileOutputStream(pdfPath);
			byte[] buffer = new byte[1024];
			int len = is.read(buffer);
			while (len != -1) {
				fos.write(buffer, 0, len);
				len = is.read(buffer);
			}
			fos.close();
			is.close();
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	//调用北京ca接口
	private boolean bjcaInterface(String encodePath,String unsignPdfPath,String signedPdfPath,String insured){
		//String fileName2 = "E:/resources/private/pdf/0021A0001555/tbts.pdf";//传入未签名PDF
		SecurityEngineDeal sed = null;
		byte[] encData1 = null;
		byte[] Pdfdata = null;
		int[] rv = new int[2]; 
		String appName = "AnySignDevice";
		try {
			SecurityEngineDeal.setProfilePath(PropertiesUtil.getProperty("bjcaConfig"));
			sed = SecurityEngineDeal.getInstance(appName);  
			List<AnywriteSignInfo> list = new ArrayList<AnywriteSignInfo>();
			encData1 = FileUtils.readFileToByteArray(new File(encodePath));
			Pdfdata = FileUtils.readFileToByteArray(new File(unsignPdfPath));
			List<byte[]> dsBy1 = new ArrayList<byte[]>();
			dsBy1.add(encData1);

			AnywriteSignInfo anywriteSignInfo1 = new AnywriteSignInfo();

			//投保单号作为bjca的业务流水号
			anywriteSignInfo1.setWoNo(insured);

			anywriteSignInfo1.setDataSource(dsBy1);
			anywriteSignInfo1.setPdfData(Pdfdata);

			anywriteSignInfo1.setInputPdfPath("");
			anywriteSignInfo1.setDocType(DocumentType.PDF);

			String extNote1 = "";
			anywriteSignInfo1.setExtNote(extNote1);

			list.add(anywriteSignInfo1);

			byte[] signedValue1=sed.getPDFAnyWriteSignByObject(anywriteSignInfo1, rv);

			if (rv[0] == 0) {
				new FileUtil().writeFile(signedValue1,signedPdfPath);
			}else{
				log("error Code = " + rv[0]);
				return false;
			}
			return true;
		}catch (Exception ee){
			ee.printStackTrace();
			return false;
		}
	}
/*
	//影像上传
	//http://localhost:9000/pad_marketing/main/shadowupload.action
	@RequestMapping("/shadowupload")
	public void shadowupload(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String policyRef = request.getParameter("policyRef");//获取保单号：
		String preprintedNo = request.getParameter("preprintedNo");//获取投保单号
		if(StringUtil.isNull(policyRef) || StringUtil.isNull(preprintedNo)){
			return ;
		}
		
		String osType = "linux";
		String os = System.getProperty("os.name");  
		if(os.toLowerCase().startsWith("win")){  
			osType = "windows";
		}  
		
		Date date = new Date();
		String flagFileName = "i"+date.getTime();
		String flagFileString_pdf_Directory = PropertiesUtil.getResourcePath()+"private/pdf/"+policyRef+"_"+preprintedNo+"/signed/";
		String flagFileString_photo_Directory = PropertiesUtil.getResourcePath()+"private/photo_temp/"+preprintedNo+"/";
		String flagFileString_pdf = flagFileString_pdf_Directory+policyRef+"_"+preprintedNo+".txt";
		String flagFileString_photo = flagFileString_photo_Directory+policyRef+"_"+preprintedNo+".txt";
		
		File flagFileString_photoDirectoryFile = new File(flagFileString_photo_Directory);
		File flagFileString_pdf_DirectoryFile = new File(flagFileString_pdf_Directory);
		File flagFile_pdf = new File(flagFileString_pdf);
		File flagFile_photo = new File(flagFileString_photo);

		if(flagFile_pdf.exists() && flagFile_photo.exists()){
			return;
		}else{
			flagFileString_pdf_DirectoryFile.mkdirs();
			flagFileString_photoDirectoryFile.mkdirs();
			flagFile_pdf.createNewFile();
			flagFile_photo.createNewFile();
			new File(flagFileString_photo_Directory+flagFileName+".txt").createNewFile();
			new File(flagFileString_pdf_Directory+flagFileName+".txt").createNewFile();
		}

		log("shadowupload_policyRef:=======================");
		//需要上传两部份资料:1，证件照片上传的photo文件。2，是已签名pdf及其若干photo
		
		String ip = getIP(request);//获取用户ip

		log("shadowupload_policyRef:"+policyRef);
		log("shadowupload_preprintedNo:"+preprintedNo);

		Map<String,List<File>> files = new HashMap<String,List<File>>();
		
		File file_party1 = new File(PropertiesUtil.getResourcePath()+"private/photo_temp/"+preprintedNo+"/");
		List<File> reditcardFiles = new ArrayList<File>();//证件1163
		List<File> nationalFiles = new ArrayList<File>();//银行卡1160
		List<File> photoFiles = new ArrayList<File>();//个人拍照1169 + 其他签字材料tiff
		ShadowUploadControllerFileFilter su = new ShadowUploadControllerFileFilter(".txt");
		//1，证件照片上传的photo文件
		if(flagFileString_photoDirectoryFile.list().length>0){
			//标识文件不存在则上传，如果存在则不上传
			File[] fileArray = file_party1.listFiles(su);
			for(File f:fileArray){
				String fileName = f.getName();
				if(fileName.contains("tbCreditcardFront")){
					reditcardFiles.add(f);
					files.put("1160",reditcardFiles);//银行卡
				}else{
					nationalFiles.add(f);
					files.put("1163",nationalFiles);//证件
				}
			}
		}

		if(flagFileString_pdf_DirectoryFile.list().length>0){
			File[] fileArray = flagFileString_pdf_DirectoryFile.listFiles();
			for(File f:fileArray){
				String fileName = f.getName();
				if(fileName.endsWith(".jpg")){
					photoFiles.add(f);
				}
			}

			for(File f:fileArray){
				String fileName = f.getName();
				File tempPath = new File(PropertiesUtil.getResourcePath()+"private/pdf/"+policyRef+"_"+preprintedNo+"/signed/");
				String tempDirectory = tempPath.getAbsolutePath()+"/";
				if("1169.pdf".equals(fileName)){
					if("linux".equals(osType)){
						log("Pdf2TifUtil.linux_exec1169");
						Pdf2TifUtil.linux_exec(f,tempDirectory,"1169");
					}
					File[] tempFiles = tempPath.listFiles(new TIFFileFilter("1169.tif"));
					if(tempFiles!=null && tempFiles.length>0){
						List<File> tifFiles = Arrays.asList(tempFiles);
						photoFiles.addAll(tifFiles);
					}
				}else if("1151.pdf".equals(fileName)){
					if("linux".equals(osType)){
						log("Pdf2TifUtil.linux_exec1151");
						Pdf2TifUtil.linux_exec(f,tempDirectory,"1151");
					}
					File[] tempFiles = tempPath.listFiles(new TIFFileFilter("1151.tif"));
					if(tempFiles!=null && tempFiles.length>0){
						List<File> tifFiles = Arrays.asList(tempFiles);
						files.put("1151", tifFiles);
					}
				}else if("1164.pdf".equals(fileName)){
					if("linux".equals(osType)){
						log("Pdf2TifUtil.linux_exec1164");
						Pdf2TifUtil.linux_exec(f,tempDirectory,"1164");
					}
					File[] tempFiles = tempPath.listFiles(new TIFFileFilter("1164.tif"));
					if(tempFiles!=null && tempFiles.length>0){
						List<File> tifFiles = Arrays.asList(tempFiles);
						files.put("1164", tifFiles);
					}
				}
			}
			if(photoFiles.size()>0){
				files.put("1169",photoFiles);
			}

			if(files.size() ==0){
				return ;
			}
			try{
				//影像上传具体实现步骤
				shadowXMLandFolderCreate(policyRef,preprintedNo,ip,files,date);
			}catch(IOException e){
				log.info("shadowupload error ,policyRef is:"+policyRef+"   preprintedNo is"+preprintedNo);
				e.printStackTrace();
			}	
		}
	}*/
/*	
	//  获取影像上传的文件集合
	private Map<String,List<File>> getFileMap(String policyRef,String preprintedNo,String start){
		Map<String,List<File>> map=new HashMap<String,List<File>>();
		String pdfPath=PropertiesUtil.getResourcePath()+"private/pdf/"+policyRef+"_"+preprintedNo+"/signed/";
		String photoPath=PropertiesUtil.getResourcePath()+"private/photo_temp/"+preprintedNo+"/";
		File file=null;
		String osType = "linux";
		String os = System.getProperty("os.name");  
		if(os.toLowerCase().startsWith("win")){  
			osType = "windows";
		} 
		if("S".equals(start)){
			file=new File(pdfPath);
			if(!file.exists() || file.isFile()){
				return null;
			}
			String tempDirectory = file.getAbsolutePath()+"/";
			List<File> photoFiles = new ArrayList<File>();
			for (File f : file.listFiles()) {
				String fileName=f.getName();
				if(fileName.endsWith(".jpg")){
					photoFiles.add(f);
				}
			}
			
			for (File f : file.listFiles()) {
				String fileName=f.getName();
				if("1169.pdf".equals(fileName)){
					if("linux".equals(osType)){
						Pdf2TifUtil.linux_exec(f,tempDirectory,"1169");
					}
					File[] tempFiles = file.listFiles(new TIFFileFilter("1169.tif"));
					if(tempFiles!=null && tempFiles.length>0){
						List<File> tifFiles = Arrays.asList(tempFiles);
						photoFiles.addAll(tifFiles);
					}
				}else if("1151.pdf".equals(fileName)){
					if("linux".equals(osType)){
						Pdf2TifUtil.linux_exec(f,tempDirectory,"1151");
					}
					File[] tempFiles = file.listFiles(new TIFFileFilter("1151.tif"));
					if(tempFiles!=null && tempFiles.length>0){
						List<File> tifFiles = Arrays.asList(tempFiles);
						map.put("1151", tifFiles);
					}
				}
				
				if(photoFiles.size()>0){
					map.put("1169", photoFiles);
				}
			}
		}else if("U".equals(start)){
			file=new File(photoPath);
			if(!file.exists() || file.isFile()){
				return null;
			}
			List<File> reditcardFiles=new ArrayList<File>();
			List<File> nationalFiles=new ArrayList<File>();
			for (File f : file.listFiles()) {
				String fileName = f.getName();
				if(fileName.contains("tbCreditcardFront")){
					reditcardFiles.add(f);
					map.put("1160",reditcardFiles);//银行卡
				}else{
					nationalFiles.add(f);
					map.put("1163",nationalFiles);//证件
				}
			}
		}else if("P".equals(start)){
			file=new File(pdfPath);
			if(!file.exists() || file.isFile()){
				return null;
			}
			String tempDirectory = file.getAbsolutePath()+"/";
			List<File> photos=new ArrayList<File>();
			for (File f : file.listFiles()) {
				String fileName=f.getName();
				if(fileName.endsWith("1164.jpg")){
					photos.add(f);
					map.put("1169", photos);
				}else if("1164.pdf".equals(fileName)){
					if("linux".equals(osType)){
						Pdf2TifUtil.linux_exec(f,tempDirectory,"1164");
					}
					File[] tempFiles = file.listFiles(new TIFFileFilter("1164.tif"));
					if(tempFiles!=null && tempFiles.length>0){
						List<File> tifFiles = Arrays.asList(tempFiles);
						map.put("1164", tifFiles);
					}
				}
			}
			File cards=new File(photoPath);
			for (File f : cards.listFiles()) {
				if(f.getName().contains("tbCreditcardFront")){
					List<File> tbCreditcardFronts=new ArrayList<File>();
					tbCreditcardFronts.add(f);
					map.put("1160", tbCreditcardFronts);
				}
			}
			File tbCreditcardFront=new File(photoPath+"tbCreditcardFront.jpg");
			if(tbCreditcardFront.isFile()){
				List<File> tbCreditcardFronts=new ArrayList<File>();
				tbCreditcardFronts.add(tbCreditcardFront);
				map.put("1160", tbCreditcardFronts);
			}
		}
		return map;
	}*/
	
	
/*
	//生成影像上传的xml文件和目录
	private void shadowXMLandFolderCreate(String policyRef,String preprintedNo,String ipHost,Map<String,List<File>> filesMap,Date date) throws IOException{
		DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
		String endPath = "i"+date.getTime();
		String folderPath = PropertiesUtil.getResourcePath()+"private/shadow_upload/"+endPath+"/";
		File folderPathFile = new File(folderPath);
		folderPathFile.mkdirs();

		FileWriter fw = new FileWriter(folderPath+"1.xml");
		Document document = DocumentHelper.createDocument();
		// 创建ImageBatch结点
		Element imageBatch = document.addElement("ImageBatch");
		// 生成ImageBatch的子接点policys
		Element policys = imageBatch.addElement("policys");
		// 生成policys的子接点policy(这里就是文件的循环了）

		Set<Entry<String,List<File>>> set = filesMap.entrySet();
		for(Entry<String,List<File>> en : set){
			String list_fileType = en.getKey();
			List<File> fileList = en.getValue();
			Element policy = policys.addElement("policy");
			Element policyNo = policy.addElement("policyNo");
				policyNo.addText(policyRef);//保单号
			Element uploadUser = policy.addElement("uploadUser");
				uploadUser.addText("app");
			Element fileType = policy.addElement("fileType");
				fileType.addText(en.getKey());
			Element taskType = policy.addElement("taskType");
				taskType.addText("01");
			Element scanTime = policy.addElement("scanTime");
				scanTime.addText(df.format(date));
			Element taskId = policy.addElement("taskId");
				taskId.addText(preprintedNo);
			Element source = policy.addElement("source");
				source.addText("2");
			Element fileNum = policy.addElement("fileNum");
				fileNum.addText(fileList.size()+"");
			Element ip = policy.addElement("ip");
				ip.addText(ipHost);
			Element files = policy.addElement("files");
			for(File f:fileList){
				Element filename = files.addElement("filename");
				String fileTempName = f.getName();
				if("1163".equals(list_fileType) || "1160".equals(list_fileType)){
					fileTempName = fileTempName.substring(fileTempName.length()-12, fileTempName.length());
				}
				filename.addText(fileTempName);
			}
		}
		// 设置文件编码
		OutputFormat xmlFormat = new OutputFormat();
		xmlFormat.setEncoding("UTF-8");
		// 设置换行
		xmlFormat.setNewlines(true);
		// 生成缩进
		xmlFormat.setIndent(true);
		// 使用1个制表符进行缩进, 可以兼容文本编辑器
		xmlFormat.setIndent("\t");
		
		// 创建写文件方法
		XMLWriter xmlWriter = new XMLWriter(fw, xmlFormat);
		// 写入文件
		xmlWriter.write(document);
		// 关闭
		xmlWriter.close();

		for(Entry<String,List<File>> en : set){
			String file_type = en.getKey();
			List<File> files = en.getValue();
			for(File f:files){
				if(f.length()>0){
					String file_name = f.getName();
					if("1163".equals(file_type) || "1160".equals(file_type)){
						file_name = file_name.substring(file_name.length()-12,file_name.length());
					}
					File endAbsolutePath = new File(folderPath+file_name);
					copyFileUsingFileChannels(f,endAbsolutePath);
				}
			}
		}
	}*/

	//自定义打印日志
	private void log(String s) throws IOException{
		String debugFile = PropertiesUtil.getResourcePath()+"debug.txt";
		FileWriter fww = new FileWriter(debugFile,true);
		BufferedWriter bw = new BufferedWriter(fww);

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		bw.write(df.format(new Date())+"    "+s);
		bw.newLine();
		bw.flush();
		bw.close();
	}
/*
	//文件复制，source文件，dest目标文件
	private static void copyFileUsingFileChannels(File source, File dest) throws IOException{
		FileChannel inputChannel = null;
		FileChannel outputChannel = null;
		try{
			inputChannel = new FileInputStream(source).getChannel();
			outputChannel = new FileOutputStream(dest).getChannel();
			outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
		}finally{
			inputChannel.close();
			outputChannel.close();
		}
	}*/
	
/*
	//获取用户ip
	private String getIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}*/
	
}